
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )

include('shared.lua')

util.PrecacheModel( "models/ascension/details/spawner.mdl" )

local SpawnSound = Sound("ambient/levels/labs/electric_explosion1.wav")

function ENT:Initialize()

	self:SetModel( "models/ascension/details/spawner.mdl" )

	self:PhysicsInit( SOLID_VPHYSICS )
	self:SetMoveType( MOVETYPE_VPHYSICS )
	self:SetSolid( SOLID_VPHYSICS )
	
	self:SetAngles( Angle(0,90,0) )
	
	self:SetNotSolid( true )
	
	self.Prop = nil
	self.Spawning = false
	
end

function ENT:ResetLastProp()
	self.Prop = nil
end

function ENT:Think()

	if ( GAMEMODE.TeamTotalProps[self:GetTeam()] > 11 and self.Prop and self.Prop:IsValid() ) then
		self.Prop:Remove()
		self:SetSkin(2)
	end

	if ( self.Prop == nil /*and GAMEMODE.TeamTotalProps[self:GetTeam()] < 19*/ ) then
		
		for k, v in pairs( ents.FindInSphere( self:GetPos(), 26 ) ) do
			if ( v:IsPlayer() ) then
				if ( v:Alive() ) then
					return false
				end
			elseif ( v:GetClass() == "ascension_prop" ) then
				return false
			end
		end
		
		self.Spawning = true
		
		local effectdata = EffectData()
			effectdata:SetOrigin( self:GetPos() )
		util.Effect( "effect_prop_spawner", effectdata )
		
		// Probably need to find a better way to do this, but we'll send the team colour as a vector
		local colour = team.GetColor( self:GetTeam() )
		effectdata:SetStart( Vector( colour.r, colour.g, colour.b ) )
		util.Effect( "effect_prop_spawner_particles", effectdata )
		self:EmitSound( SpawnSound )
		
		self.Prop = ents.Create( "ascension_prop" )
		self.Prop:SetPos( self:GetPos() + Vector(0,0,60) )
		self.Prop:SetTeam( self:GetTeam() )
		timer.Simple(0.5, function()
			if ( self.Prop and self.Prop:IsValid() ) then
				self.Prop:Spawn()
				self:SetSkin(1)
				self.Spawning = false
				
				GAMEMODE.TeamTotalProps[self:GetTeam()] = GAMEMODE.TeamTotalProps[self:GetTeam()] + 1
			end
		end )
		
	elseif ( self.Prop and self.Prop:IsValid() and !self.Spawning ) then
		
		// If our prop has moved away from us, we'll presume someone picked up the prop and spawn another.
		//if ( self:GetPos():Distance( self.Prop:GetPos() ) > 65 ) then
		if (self.Prop:IsActive()) then
			self.Prop = nil
			self:SetSkin(3)
		end
	
	end
	
	self:NextThink( CurTime() + 0.2 )
	
	return true
	
end

